/**
 * @ngdoc module
 * @name assignment.controllers
 * @description
 *   任务指派模块控制器
 */
angular.module('assignment.controllers', [])

  .controller('AssignmentIndexCtrl', function($scope, $ionicModal, $ionicLoading, User, Assignment, Utils) {
    $ionicLoading.show();
    User.getAuthority().success(function(res){
      if(res.isSuccess){
        //检查用户是否有权限使用该模块
        if(res.data.assignment){
          Assignment.getSubordinates({ uid: User.uid })
            .success(function(res) {
            });

          // 下属列表 modal
          $ionicModal.fromTemplateUrl('templates/assignment/subordinate-modal.html', {
            scope: $scope,
            animation: 'slide-in-up'
          }).then(function(modal) {
            $scope.modal = modal;
          });

          $scope.subordinates = [];

          // 打开下属列表 modal
          $scope.openSubordinateModal = function($event, uid) {
            $event.stopPropagation();
            $event.preventDefault();
            if(!uid) {
              return false;
            }
            Assignment.getSubordinates({ uid: uid })
              .success(function(res) {
                $scope.subordinates.push(res.users);
              });
            $scope.modal.show();
          };

          $scope.backSubordinateModal = function() {
            $scope.subordinates.pop();
          };

          $scope.closeSubordinateModal = function() {
            $scope.subordinates = [];
            $scope.modal.hide();
          };

          $scope.$on('$ionicView.leave', function() {
            $scope.subordinates = [];
            $scope.modal.hide();
          });

        } else {
          Utils.promptNoPermission();
        }
      }
    }).finally($ionicLoading.hide)
  })

/**
 * @ngdoc controller
 * @name AssignmentUnfinishedCtrl
 * @module assignment.controllers
 * @description
 *   任务指派-未完成列表页控制器
 */
  .controller('AssignmentUnfinishedCtrl', function($scope, $state, $stateParams, $ionicActionSheet, $ionicLoading, $ionicModal, User, Utils, IbPopup, Assignment, AssignmentUnfinished) {
    $ionicLoading.show();

    if($stateParams.uid) {
      $scope.userName = '（' + User.getUser($stateParams.uid).realname + '）'

      AssignmentUnfinished.getSubList($stateParams)
        .success(function(res) {
          $scope.data = res;
        })
        .finally($ionicLoading.hide);
    } else {
      AssignmentUnfinished.get()
        .success(function(res) {
          $scope.data = res;
        })
        .finally($ionicLoading.hide);
      $scope.myself = true;
    }

    $scope.isDateTimeLocalSupport = Utils.isDateTimeLocalSupport;

    // 是否已过期
    $scope.isOverdue = function(item) {
      return item &&
        item.endtime &&
        Date.now() > item.endtime * 1000;
    };

    // 是否设置了提醒
    $scope.haveRemind = function(item) {
      return item &&
          // 过期时不显示提醒
        !$scope.isOverdue(item) &&
        item.remindtime > 0;
    };

    // Modal: 延期申请
    $ionicModal.fromTemplateUrl('templates/assignment/delay-apply-modal.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.delayModal = modal;
    });

    // Modal: 取消申请
    $ionicModal.fromTemplateUrl('templates/assignment/cancel-apply-modal.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.cancelModal = modal;
    });

    // 打开任务延期申请 Modal
    $scope.openDelayApplyModal = function(item) {
      $scope.delayApplySubmitting = false;
      $scope.delayData = {
        id: item.assignmentid,
        delayReason: '',
        isDesignee: User.uid == item.designeeuid,
        starttime: new Date(item.starttime * 1000),
        endtime: new Date(item.endtime * 1000)
      };

      $scope.delayModal.show();
      return true;
    };

    // 任务延期，负责人申请延期、指派人延期放在一起处理
    $scope.applyDelay = function(isDesignee) {
      // 是指派人时直接延期、负责人则需通过申请的方式
      var func = isDesignee ? AssignmentUnfinished.delay : AssignmentUnfinished.applyDelay;
      $scope.delayApplySubmitting = true;

      func.call(AssignmentUnfinished, angular.extend({}, $scope.delayData, {
        // 格式化日期
        starttime: $scope.delayData.starttime ? Assignment.formatDatetime($scope.delayData.starttime) : '',
        endtime: $scope.delayData.endtime ? Assignment.formatDatetime($scope.delayData.endtime) : ''
      }))
        .success(function(res) {
          if(res.isSuccess) {
            $scope.delayModal.hide();
          }
        })
        .finally(function() {
          $scope.delayApplySubmitting = false;
        });
    };

    // 打开任务取消申请 Modal
    $scope.openCancelApplyModal = function(item) {
      $scope.cancelApplySubmitting = false;
      $scope.cancelData = {
        id: item.assignmentid,
        cancelReason: ''
      };

      $scope.cancelModal.show();
      return true;
    };

    // 负责人申请任务取消
    $scope.applyCancel = function() {
      $scope.cancelApplySubmitting = true;
      AssignmentUnfinished.applyCancel($scope.cancelData)
        .success(function(res) {
          if(res.isSuccess) {
            $scope.cancelModal.hide();
          }
        })
        .finally(function() {
          $scope.cancelApplySubmitting = false;
        });
    };

    // 指派人取消任务
    $scope.cancel = function(item) {
      $ionicLoading.show();

      AssignmentUnfinished.cancel({ id: item.assignmentid })
        .success(function(res) {
          if(res.isSuccess) {
            item.status = 4;
          }
        })
        .finally($ionicLoading.hide);

      return true;
    };

    $scope.edit = function(item) {
      $state.go('assignment.edit', { id: item.assignmentid });
      return true;
    };

    // 删除任务
    $scope.remove = function(item) {
      IbPopup.confirm({ title: '确定要删除该任务？' })
        .then(function(res) {
          if(res) {
            $ionicLoading.show();
            Assignment.remove({ id: item.assignmentid })
              .success(function(res) {
                if(res.isSuccess) {
                  item.isRemove = true;
                }
              })
              .finally($ionicLoading.hide)
          }
        });
      return true;
    };

    // 催办
    $scope.urge = function(item){
      $ionicLoading.show();

      AssignmentUnfinished.urge({ id: item.assignmentid })
        .success(function(res) {
          if(res.isSuccess) {
            IbPopup.tip(res.msg);
          }
        })
        .finally($ionicLoading.hide);

      return true;
    };

    // 重启任务
    $scope.restart = function(item){
      $ionicLoading.show();

      AssignmentUnfinished.restart({ id: item.assignmentid })
        .success(function(res) {
          if(res.isSuccess) {
            item.status = 1;
          }
        })
        .finally($ionicLoading.hide);

      return true;
    };

    // 完成任务
    $scope.done = function(item){
      $ionicLoading.show();

      AssignmentUnfinished.done({ id: item.assignmentid })
        .success(function(res) {
          if(res.isSuccess) {
            item.status = 2;
          }
        })
        .finally($ionicLoading.hide);

      return true;
    };

    // 设置提醒 Modal
    $ionicModal.fromTemplateUrl('templates/assignment/remind-modal.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.remindModal = modal;
    });

    // 打开设置提醒 Modal
    $scope.openRemingModal = function(item) {
      $scope.remindSubmitting = false;

      $scope.remindData = {
        id: item.assignmentid,
        remindContent: ''
      };

      // 如果已设置提醒，将获取之前提醒的数据
      if(item.remindtime > 0) {
        AssignmentUnfinished.getRemindData({ id: item.assignmentid })
          .success(function(res) {
            if(res.isSuccess) {
              $scope.remindData.remindContent = res.data.content;
              $scope.remindData.remindTime = Assignment.convertDateTime(res.data.reminddate + ' ' + res.data.remindtime);
            }
          });
      }

      $scope.remindModal.show();
      return true;
    };

    $scope.remind = function(item) {
      $scope.remindSubmitting = true;
      AssignmentUnfinished.remind($scope.remindData)
        .success(function(res) {
          if(res.isSuccess) {
            $scope.remindModal.hide();
          }
        })
        .finally(function() {
          $scope.remindSubmitting = false;
        });
    }


    var buttons = {
      edit:        { text: '编辑', handler: $scope.edit },
      remove:      { text: '删除', handler: $scope.remove },
      cancel:      { text: '取消任务', handler: $scope.cancel },
      applyCancel: { text: '申请取消', handler: $scope.openCancelApplyModal },
      delay:       { text: '延期任务', handler: $scope.openDelayApplyModal },
      applyDelay:  { text: '申请延期', handler: $scope.openDelayApplyModal },
      remind:      { text: '设置提醒', handler: $scope.openRemingModal },
      urge:        { text: '催办', handler: $scope.urge },
      done:        { text: '完成', handler: $scope.done },
      restart:     { text: '重启任务', handler: $scope.restart },
      // stamp:       { text: '评价', handler: $scope.stamp }
    };

    function createMenuOptions(item) {
      var roleText = Assignment.getRoleText(item);

      var options = {
        titleText: '任务操作' + (roleText ? '（' + roleText + '）' : ''),
        buttons: [],
        buttonClicked: function(index, opts) {
          return opts.handler.call(null, item);
        },
        cancelText: '取消'
      }

      var ops = Assignment.getEnableOperation(item);
      if(ops.length) {
        angular.forEach(ops, function(op) {
          // 删除按钮特殊处理
          if(op == 'remove') {
            options.destructiveText = buttons[op].text;
            options.destructiveButtonClicked = function() {
              return buttons[op].handler(item);
            };
          } else {
            if(buttons[op]) {
              options.buttons.push(buttons[op]);
            }
          }
        });
      }

      return options;
    }

    $scope.showMenu = function(item) {
      $scope.hideMenu = $ionicActionSheet.show(createMenuOptions(item));
    };

    $scope.$on('$ionicView.leave', function() {
      $scope.delayModal.hide();
      $scope.cancelModal.hide();
      $scope.remindModal.hide();
    });

    $scope.$on('$destroy', function() {
      $scope.delayModal.remove();
      $scope.cancelModal.remove();
      $scope.remindModal.remove();
    });
  })

/**
 * @ngdoc controller
 * @name AssignmentFinishedCtrl
 * @module assignment.controllers
 * @description
 *   任务指派-已完成列表页控制器
 */
  .controller('AssignmentFinishedCtrl', function($scope, $filter, $ionicLoading, $ionicActionSheet, User, AssignmentFinished, AssignmentUnfinished) {
    $scope.prop = {};

    // 初始化列表，首次进来时自动加载数据
    $scope.init = function() {
      // 若没有页面缓存，重置查询条件，直接加载第一页的数据
      if(!$scope.list.hasItems()) {
        $scope.list.refresh();
      }
    };

    // 刷新列表
    $scope.refresh = function() {
      $scope.prop.keyword = '';
      $scope.list.refresh()
        .finally(function() {
          $scope.$broadcast('scroll.refreshComplete');
        });
    };

    $scope.list = AssignmentFinished;
    $scope.init();

    // 判断是否指派人
    $scope.isDesignee = function(item) {
      return item.designeeuid == User.uid;
    };

    var dateFilter = $filter('date');
    // 根据“完成时间”分组
    $scope.groupByFinishTime = function(items) {
      var ret = [];
      angular.forEach(items, function(item, index) {
        var finishDate = dateFilter(item.finishtime * 1000, 'yyyy-MM-dd EEEE');
        // 判断完成日期是否与前一条相同，若是则放进同一个组
        if(ret.length && finishDate == ret[ret.length - 1].finishDate) {
          ret[ret.length - 1].items.push(item);
          // 若不是，则新建一个分组
        } else {
          ret.push({ finishDate: finishDate, items: [item] });
        }
      });
      return ret;
    };

    $scope.$watchCollection('list.items', function(items) {
      $scope.groupedItems = $scope.groupByFinishTime(items);
    });

    // 重启任务
    $scope.restart = function(item){
      $ionicLoading.show();

      AssignmentUnfinished.restart({ id: item.assignmentid })
        .success(function(res) {
          if(res.isSuccess) {
            $scope.list.remove(item.assignmentid);
          }
        })
        .finally($ionicLoading.hide);

      return true;
    };

    $scope.showMenu = function(item) {
      var conf = {
        titleText: '任务操作',
        buttons: [
          { text: '重启任务', handler: $scope.restart }
        ],
        buttonClicked: function(index, opts) {
          return opts.handler.call(null, item);
        },
        cancelText: '取消'
      };
      $scope.hideMenu = $ionicActionSheet.show(conf);
    };

    // 获取图章路径
    $scope.getStampPath = function(value) {
      return Assignment.getStampPath(value, $scope.stamps);
    };
  })

/**
 * @ngdoc controller
 * @name AssignmentCreateCtrl
 * @module assignment.controllers
 * @description
 *   任务指派-新建任务页控制器
 */
  .controller('AssignmentCreateCtrl', function($scope, $timeout, $state, $filter, $ionicLoading, Settings, Utils, User, Assignment, IbPopup) {

    $scope.isDateTimeLocalSupport = Utils.isDateTimeLocalSupport;

    var submitting = false;

    // 重置表单项
    function resetForm (){
      var date = new Date();
      $scope.form = {
        chargeuid: User.uid,
        starttime: date,
        // 结束时间默认为 3 天后
        endtime: new Date(+date + 259200000)
      };
      submitting = false;
    }

    $scope.isDisabledSubmit = function() {
      return submitting || !($scope.assignmentForm && $scope.assignmentForm.$valid);
    };

    $scope.save = function() {
      var form = Assignment.correctFormData($scope.form);

      $ionicLoading.show();
      submitting = true;

      Assignment.create(form)
        .success(function() {
          resetForm();
          IbPopup.confirm({ title: '新建任务成功', okText:'去看看' })
            .then(function(res) {
              if(res) {
                $state.go('assignment.unfinished');
              }
            })
        })
        .error(Settings.requestError)
        .finally(function() {
          $ionicLoading.hide();
          submitting = false;
        })
    };

    resetForm();
  })

/**
 * @ngdoc controller
 * @name AssignmentEditCtrl
 * @module assignment.controllers
 * @description
 *   任务指派-编辑任务页控制器
 */
  .controller('AssignmentEditCtrl', function($scope, $stateParams, $timeout, $filter, $ionicLoading, $ionicHistory, Settings, Utils, User, IbPopup, Assignment) {

    $scope.isDateTimeLocalSupport = Utils.isDateTimeLocalSupport;

    var submitting = false;

    $scope.isDisabledSubmit = function() {
      return submitting || !($scope.assignmentForm && $scope.assignmentForm.$valid);
    };

    $scope.save = function() {
      var form = Assignment.correctFormData($scope.form);

      $ionicLoading.show();
      submitting = true;

      Assignment.update($stateParams.id, form)
        .success(function() {
          $ionicHistory.goBack();
        })
        .error(Settings.requestError)
        .finally(function() {
          $ionicLoading.hide();
          submitting = false;
        })
    };

    // 获取当前任务的相关信息
    $ionicLoading.show();
    Assignment.get($stateParams)
      .success(function(res) {
        // 获取成功后，添加数据到 form 对象上
        if(res.isSuccess) {
          $scope.form = {
            subject: res.data.subject,
            chargeuid: User.removePrefix(res.data.chargeuid),
            participantuid: User.removePrefix(res.data.participantuid),
            starttime: res.data.starttime ?
              new Date(res.data.starttime) :
              '',
            endtime: new Date(res.data.endtime),
            description: res.data.description
          };
          // 获取出错时，提示引导用户并返回上一页
        } else {
          IbPopup.alert({ title: res.msg })
            .then(function() {
              $ionicHistory.goBack();
            });
        }
      })
      .error(Settings.requestError)
      .finally($ionicLoading.hide)
  })

/**
 * @ngdoc controller
 * @name AssignmentDetailCtrl
 * @module assignment.controllers
 * @description
 *   任务指派-查看任务页控制器
 */
  .controller('AssignmentDetailCtrl', function($scope, $stateParams, $ionicLoading, $ionicHistory, $ionicModal, Settings, User, IbPopup, Assignment, AssignmentUnfinished) {
    var assignment = {};
    $scope.submitting = false;

    // 是否已过期
    $scope.isOverdue = function() {
      return assignment &&
        assignment.endtime &&
        Date.now() > assignment.endtime * 1000;
    };

    // 是否设置了提醒
    $scope.haveRemind = function() {
      return assignment && assignment.remindtime > 0;
    };

    // 完成任务
    $scope.done = function() {
      $scope.submitting = true;

      AssignmentUnfinished.done({ id: assignment.assignmentid })
        .success(reloadInfo)
        .finally(function() {
          $scope.submitting = false;
        });
    };

    // 重启任务
    $scope.restart = function() {
      $scope.submitting = true;

      AssignmentUnfinished.restart({ id: assignment.assignmentid })
        .success(reloadInfo)
        .finally(function() {
          $scope.submitting = false;
        });
    };

    // 催办
    $scope.urge = function() {
      $scope.submitting = true;

      AssignmentUnfinished.urge({ id: assignment.assignmentid })
        .success(function(res) {
          if(res.isSuccess) {
            IbPopup.tip(res.msg);
          }
        })
        .finally(function() {
          $scope.submitting = false;
        });
    };

    function _confirm(options, onresolve, onreject) {
      options = angular.extend({
        buttons: [
          {
            text: '拒绝',
            onTap: onreject
          },
          {
            text: '同意',
            type: 'button-positive',
            onTap: onresolve
          }
        ]
      }, options);
      return IbPopup.confirm(options)
    }

    function confirmDelayApply(data) {
      return _confirm({
        title: '任务延期申请',
        templateUrl: 'templates/assignment/deal-delay-apply.html',
        scope: $scope
      }, function() {

        AssignmentUnfinished.dealDelayApply({ id: assignment.assignmentid, agree: 1 })
          .success(reloadInfo);

      }, function() {
        AssignmentUnfinished.dealDelayApply({ id: assignment.assignmentid, agree: 0 });
      })
    }

    function confirmCancelApply(data){
      return _confirm({
        title: '任务取消申请',
        templateUrl: 'templates/assignment/deal-cancel-apply.html',
        scope: $scope
      }, function() {

        AssignmentUnfinished.dealCancelApply({ id: assignment.assignmentid, agree: 1 })
          .success(reloadInfo);

      }, function() {
        AssignmentUnfinished.dealCancelApply({ id: assignment.assignmentid, agree: 0 });
      });
    }

    // 获取当前任务的相关信息
    function loadInfo() {
      $ionicLoading.show();
      Assignment.getFullInfo($stateParams)
        .success(function(res) {
          if(res.isSuccess) {
            $scope.data = res.data;
            $scope.assignment = assignment = res.data.assignment;
            $scope.stamps = res.stamps;

            $scope.isDesignee = (User.uid == assignment.designeeuid);
            $scope.isCharge = (User.uid == assignment.chargeuid);

            // 处理“延时申请”和“取消申请”
            var applyData = res.data.applyData;
            if($scope.isDesignee && applyData && applyData.id) {
              // 有返回开始时间时，判断为“延时申请”
              if(applyData.startTime) {
                confirmDelayApply(applyData);
                // 否则判断为“取消申请”
              } else {
                confirmCancelApply(applyData);
              }
            }
            // 获取出错时，提示引导用户并返回上一页
          } else {
            IbPopup.alert({ title: res.msg })
              .then(function() {
                $ionicHistory.goBack();
              });
          }
        })
        .error(Settings.requestError)
        .finally($ionicLoading.hide)
    }

    function reloadInfo(res) {
      if(res.isSuccess) {
        loadInfo();
      }
    }

    loadInfo();

    // 获取图章路径
    $scope.getStampPath = function(value) {
      return Assignment.getStampPath(value, $scope.stamps);
    };

    // 图章 Modal
    $ionicModal.fromTemplateUrl('templates/assignment/stamp-modal.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.stampModal = modal;
    });

    $scope.selectStamp = function(value) {
      Assignment.stamp({ id: $scope.assignment.assignmentid, stamp: value })
        .success(reloadInfo);
      $scope.stampModal.hide();
    };

    $scope.$on('$ionicView.leave', function() {
      $scope.stampModal.hide();
    });

    $scope.$on('$destroy', function() {
      $scope.stampModal.remove();
    });
  })
